import os
from configparser import NoSectionError, NoOptionError, Error

from git.repo import Repo
from git.repo.fun import is_git_dir
from git.config import GitConfigParser

class GitRepository(object):
    """
    git仓库管理
    # 参考文章：python调用git
    # https://blog.csdn.net/dreams_dream/article/details/128524357
    """

    def __init__(self, local_path, repo_url, branch=None,bare:bool=False):
        self.local_path = local_path
        self.repo_url = repo_url
        self.repo = None
        self.bare = bare
        self.initial(repo_url, branch)

    def initial(self, repo_url, branch):
        """
        初始化git仓库
        :param repo_url:
        :param branch:
        :return:
        """
        if not os.path.exists(self.local_path):
            os.makedirs(self.local_path)

        git_local_path = os.path.join(self.local_path, '.git')
        if not is_git_dir(git_local_path):
            self.repo = Repo.clone_from(repo_url, to_path=self.local_path, branch=branch,bare=self.bare)
        else:
            self.repo = Repo(self.local_path)

    def pull(self):
        """
        从线上拉最新代码
        :return:
        """
        self.repo.git.pull()

    def branches(self):
        """
        获取所有分支
        :return:
        """
        branches = self.repo.remote().refs
        return [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]

    def commits(self):
        """
        获取所有提交记录
        :return:
        """
        commit_log = self.repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',
                                       max_count=10,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        # print(self.repo.heads.master.commit,type(self.repo.heads.master.commit),type(str(self.repo.heads.master.commit)))
        return [eval(item) for item in log_list]

    def new_master_commits(self):
        """获取主分支的最后一次提交记录"""
        return str(self.repo.heads.master.commit)[:7]

    def tags(self):
        """
        获取所有tag
        :return:
        """
        return [tag.name for tag in self.repo.tags]

    def change_to_branch(self, branch):
        """
        切换分值
        :param branch:
        :return:
        """
        self.repo.git.checkout(branch)

    def change_to_commit(self, branch, commit):
        """
        切换commit
        :param branch:
        :param commit:
        :return:
        """
        self.change_to_branch(branch=branch)
        self.repo.git.reset('--hard', commit)

    def change_to_tag(self, tag):
        """
        切换tag
        :param tag:
        :return:
        """
        self.repo.git.checkout(tag)

    def get_log_1(self):
        """获取当前版本信息"""
        commit_hash = self.repo.head.object.hexsha
        commit_message = self.repo.head.object.message
        commit_author = self.repo.head.object.author.name
        commit_time = self.repo.head.object.authored_datetime

        print(f"Commit hash: {commit_hash}")
        print(f"Commit message: {commit_message}")
        print(f"Commit author: {commit_author}")
        print(f"Commit time: {commit_time}")
    @staticmethod
    def del_proxy():
        try:
            gitconfigparser=GitConfigParser(os.path.normpath(os.path.expanduser("~/.gitconfig")),read_only=True)
            gitconfigparser.get_value("http","proxy")
            gitconfigparser=GitConfigParser(os.path.normpath(os.path.expanduser("~/.gitconfig")),read_only=False)
            gitconfigparser.remove_option("http","proxy")
            gitconfigparser.remove_option("https","proxy")
            gitconfigparser.release()
        except Error:
            print("",end="")
    @staticmethod
    def add_proxy(ip_port):
        try:
            gitconfigparser=GitConfigParser(os.path.normpath(os.path.expanduser("~/.gitconfig")),read_only=True)
            gitconfigparser.get_value("http","proxy")
        except Error:
            gitconfigparser=GitConfigParser(os.path.normpath(os.path.expanduser("~/.gitconfig")),read_only=False)
            gitconfigparser.add_value("http","proxy",ip_port)
            gitconfigparser.add_value("https","proxy",ip_port)
            gitconfigparser.release()


if __name__ == '__main__':

    # 本地仓库位置
    local_path = "D:\git\\auto_test"
    # 远程仓库位置
    remote_path = 'https://gitee.com/auto_test.git'
    git = GitRepository(local_path, remote_path)